package mybatisTest.test.myclassloader;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class MyClassLoader extends ClassLoader {

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] bytes=null;
        try {
             bytes = loadData(name);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return defineClass(name,bytes,0,bytes.length);
    }

    public byte[] loadData(String name) throws IOException {
        String path="D:\\temp\\"+name+".class";
        FileInputStream fileInputStream=new FileInputStream(path);
        ByteArrayOutputStream bytes=new ByteArrayOutputStream();
        byte[] buffer=new byte[4096];
        int readc=0;
        while ((readc=fileInputStream.read(buffer))!=-1){
            bytes.write(buffer,0,readc);
        }
        return bytes.toByteArray();
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        Class<?> demoClass = new MyClassLoader().findClass("DemoClass");
        Method say = demoClass.getMethod("run");
        Object o = demoClass.newInstance();
        say.invoke(o);
    }
}
